import axios from 'axios'
import {Message} from 'element-ui'
import store from '@/store'
import {getToken} from '@/utils/auth'

// create an axios instance
const requests = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 5000 // request timeout
})

// request interceptor
requests.interceptors.request.use(
  config => {
    // do something before request is sent

    if (store.getters.token) {
      // let each request carry token
      // ['X-Token'] is a custom headers key
      // please modify it according to the actual situation
      config.headers['X-Token'] = getToken()
    }
    return config
  },
  error => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

function errorMsgHandle(code) {
  let msg = '服务器故障'
  if (code === 2100) {
    msg = '登录已过期，请重新登录'
  } else if (code === 2201) {
    msg = '数据已存在'
  } else if (code === 2001 || code === 2005) {
    msg = '用户名或密码错误'
  } else if (code === 3110) {
    msg = '请求参数错误'
  }
  Message({
    message: msg,
    type: 'error',
    duration: 5 * 1000
  })
}

// response interceptor
requests.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
   */

  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
  response => {
    const result = response.data
    if (result.code !== 0) {
      errorMsgHandle(result.code)
      return Promise.reject(new Error(result.msg ? result.code : result.msg || '返回错误无Message'))
    } else {
      return result
    }
  },
  error => {
    console.log('httpResponse返回错误:', error) // for debug
    let errorMsg = error.message;
    if (error.response.status === 403 || error.response.status === 401 || error.response.status === 405) {
      errorMsg = "未授权,请联系管理员";
    }
    Message({
      message: errorMsg || '服务器返回错误',
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)

export default requests
